<?php
namespace Xxfaxy\DryBundle\Services;

class CommonFunction
{

    protected $container;

    public function __construct($service_container)
    {
        $this->container = $service_container;
    }

    /*view*/
    public function getChoice($key, $isReturn = false)
    {
        $em = $this->container->get('doctrine.orm.entity_manager');
        $entity = $em->getRepository('XxfaxyDryBundle:Choice')->findOneByDryKey($key);
        $all = json_decode($entity->getDryValue(), true);
        $choice = array();
        foreach($all as $v){
            if($v['status'] == '1'){
                if($isReturn){
                    $choice[$v['key']] = $v;
                }
                else{
                    $choice[$v['key']] = $v['value'];
                }
            }
        }
        return $choice;
    }

    /*view*/
    public function getSetting()
    {
        $em = $this->container->get('doctrine.orm.entity_manager');
        $entityList = $em->getRepository('XxfaxyDryBundle:Setting')->findAll();
        $data = array();
        foreach($entityList as $entity){
            $data[$entity->getDryName()] = $entity->getDryValue();
        }
        return json_decode(json_encode($data));
    }

    /*view*/
    /*真的不需要break语句退出循环*/
    public function getIp()
    {
        $ip = '127.0.0.1';
        $list = array('REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP');
        foreach($list as $k){
            if(isset($_SERVER[$k]) && !empty($_SERVER[$k])){
                $ip = $_SERVER[$k];
            }
        }
        return $ip;
    }

    /*view*/
    public function getCategoryUpdateSortSql($config = array())
    {
        $table = isset($config['table'])?$config['table']:'menu';
        $parentField = isset($config['parentField'])?$config['parentField']:'dryParent';
        $gradeField = isset($config['gradeField'])?$config['gradeField']:'dryGrade';
        $sortField = isset($config['sortField'])?$config['sortField']:'drySort';
        $dataSortField = isset($config['dataSortField'])?$config['dataSortField']:'dryDataSort';
        $sql = array();
        $sql[] = "
        update {$table} m
        set m.{$dataSortField}=concat(m.{$gradeField}+1000,m.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000)
        where m.{$gradeField}=1
        ";
        $sql[] = "
        update {$table} m
        left join {$table} p on p.id=m.{$parentField}
        set m.{$dataSortField}=concat(p.{$gradeField}+1000,p.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000)
        where m.{$gradeField}=2
        ";
        $sql[] = "
        update {$table} m
        left join {$table} p on p.id=m.{$parentField}
        left join {$table} pp on pp.id=p.{$parentField}
        set m.{$dataSortField}=concat(pp.{$gradeField}+1000,pp.{$sortField}+1000,p.{$gradeField}+1000,p.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000)
        where m.{$gradeField}=3
        ";
        $sql[] = "
        update {$table} m
        left join {$table} p on p.id=m.{$parentField}
        left join {$table} pp on pp.id=p.{$parentField}
        left join {$table} ppp on ppp.id=pp.{$parentField}
        set m.{$dataSortField}=concat(ppp.{$gradeField}+1000,ppp.{$sortField}+1000,pp.{$gradeField}+1000,pp.{$sortField}+1000,p.{$gradeField}+1000,p.{$sortField}+1000,m.{$gradeField}+1000,m.{$sortField}+1000)
        where m.{$gradeField}=4
        ";
        return $sql;
    }

    /*view*/
    private function getAllTranslation()
    {
        $yml = $this->container->get('service.parse.yaml');
        $bundlePath = $this->container->getParameter('bundle_path');
        $locale = $this->container->getParameter('locale');
        $file = "{$bundlePath}/Resources/translations/XxfaxyDryBundle.{$locale}.yml";
        $array = $yml->load($file);
        return $array;
    }

    /*view*/
    public function translation($name)
    {
        $list = $this->getAllTranslation();
        if(isset($list[$name])){
            return $list[$name];
        }
        else{
            return $name;
        }
    }

    /*view*/
    public function getFormData($post)
    {
        $temp = array_keys($post);
        return $post[$temp[0]];
    }

    /*view*/
    public function getScaleWidthHeight($limit_width, $limit_height, $source_width, $source_height)
    {
        $wh = array();
        if($source_width<=$limit_width && $source_height<=$limit_height){
            $wh['width'] = $source_width;
            $wh['height'] = $source_height;
        }
        else{
            $w = $source_width/$limit_width;
            $h = $source_height/$limit_height;
            if($w>$h){
                $wh['width'] = $limit_width;
                $wh['height'] = ($w>=1?($source_height/$w):($source_height*$w));
            }
            elseif($w<$h){
                $wh['width'] = ($h>=1?($source_width/$h):($source_width*$h));
                $wh['height'] = $limit_height;
            }
            else{
                $wh['width'] = $limit_width;
                $wh['height'] = $limit_height;
            }
            $wh['width'] = floor($wh['width']);
            $wh['height'] = floor($wh['height']);
        }
        return $wh;
    }

    /*view*/
    public function sendYunPianMessageCode($apikey, $tplId, $mobilePhone, $messageCode)
    {
        $messageCode = urlencode($messageCode);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/tpl_single_send.json');
        $data = array(
            'apikey' => $apikey,
            'tpl_id' => $tplId,
            'mobile' => $mobilePhone,
            'tpl_value' => "#code#={$messageCode}"
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $result = curl_exec($ch);
        if($result == ''){
            $result = curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

    public function sendAliYunMessageCode($accessKeyId, $accessKeySecret, $PhoneNumbers, $SignName, $TemplateCode, $code)
    {
        $parameter = [
            'PhoneNumbers' => $PhoneNumbers,/*短信接收号码*/
            'SignName' => $SignName,/*短信签名*/
            'TemplateCode' => $TemplateCode,/*短信模板Code*/
            'TemplateParam' => json_encode(['code' => $code], JSON_UNESCAPED_UNICODE),
            'RegionId' => 'cn-hangzhou',
            'Action' => 'SendSms',
            'Version' => '2017-05-25',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => uniqid(mt_rand(0, 0xffff), true),
            'SignatureVersion' => '1.0',
            'AccessKeyId' => $accessKeyId,
            'Timestamp' => gmdate("Y-m-d\TH:i:s\Z"),
            'Format' => 'JSON'
        ];
        ksort($parameter);
        $sorted = '';
        foreach($parameter as $k => $v){
            $k = $this->sendAliYunMessageCodeEncode($k);
            $v = $this->sendAliYunMessageCodeEncode($v);
            $sorted .= "&{$k}={$v}";
        }
        $sign = base64_encode(hash_hmac('sha1', "GET&%2F&" . $this->sendAliYunMessageCodeEncode(substr($sorted, 1)), $accessKeySecret . '&', true));
        $sign = $this->sendAliYunMessageCodeEncode($sign);
        $url = "http://dysmsapi.aliyuncs.com/?Signature={$sign}{$sorted}";
        $content = file_get_contents($url);
        $content = json_decode($content, true);
        return $content;
        /*
        {
            "Message": "OK",
            "RequestId": "CA9CFE00-1B93-400D-91E5-8B08F07680BE",
            "BizId": "310517820779519263^0",
            "Code": "OK"
        }
        */
    }

    private function sendAliYunMessageCodeEncode($string)
    {
        $result = urlencode($string);
        $result = preg_replace("/\+/", "%20", $result);
        $result = preg_replace("/\*/", "%2A", $result);
        $result = preg_replace("/%7E/", "~", $result);
        return $result;
    }

    /*view*/
    public function clearDir($dir)
    {
        if(file_exists($dir) && $handle = opendir($dir)){
            while(false !== ($item = readdir($handle))){
                if($item != '.' && $item != '..'){
                    $path = $dir . '/' . $item;
                    if(file_exists($path) && is_dir($path)){
                        $this->clearDir($path);
                    }
                    else{
                        @unlink($path);
                    }
                }
            }
            @closedir($handle);
        }
    }

    /*view*/
    public function isStartWith($tring, $test)
    {
        return substr(md5(time()).$tring, 32, strlen($test)) == $test;
    }

    /*view*/
    public function IsMobile()
    {
        $httpUserAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strpos($httpUserAgent, 'iphone') || strpos($httpUserAgent, 'android')){
            return true;
        }
        else{
            return false;
        }
    }

    /*view*/
    function getDateList($start_date, $end_date, $key_is_date = false)
    {
        $daySeconds = 86400;
        $startTimestamp = strtotime($start_date);
        $endTimestamp = strtotime($end_date);
        $span = intval(($endTimestamp - $startTimestamp) / $daySeconds) + 1;
        $list = array();
        for($i = 0; $i < $span; $i++){
            $temp = $startTimestamp + ($i * $daySeconds);
            $temp = date('Y-m-d', $temp);
            if($key_is_date){
                $list[$temp] = $temp;
            }
            else{
                $list[] = $temp;
            }
        }
        return $list;
    }

    public function email($subject, $from, $to, $body)
    {
        $mailer = $this->container->get('mailer');
        $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom($from)->setTo($to)->setBody($body, 'text/html');
        return $mailer->send($message);
    }

    public function jsonEncodeForApi($array)
    {
        return json_encode($array, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }

    public function makeOrder($time = 0)
    {
        if(! $time){
            $time = time();
        }
        return date('YmdHis', $time) . bin2hex(uniqid());
    }

    public function getDateAndTime()
    {
        $time = date('Y-m-d H:i:s');
        $date = substr($time, 0, 10);
        return ['date' => $date, 'time' => $time];
    }

    public function passwordHash($text)
    {
        return password_hash($text, PASSWORD_DEFAULT);
    }

    public function passwordVerify($text, $hash)
    {
        return password_verify($text, $hash);
    }

}
